package action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class UploadAction extends ActionSupport{
    private String title;
    private File file;
    private String fileContentType;
    private String fileFileName;
    private String savePath;
//    private String allowTypes;

    @Override
    public String execute() throws Exception {
        if(getFile()==null){
            return "index";
        }
        File dir = new File(getSavePath());
        if(!dir.exists()){
            dir.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(getSavePath()+"/"+getFileFileName());
        FileInputStream fis = new FileInputStream(getFile());
        byte[] buffer = new byte[1024];
        int len;
        while((len = fis.read(buffer))>0){
            fos.write(buffer,0,len);
        }
        return SUCCESS;
    }

//    private boolean filter(String[] types){
//        String type = getFileContentType();
//        for(String t : types){
//            if(t.equals(type)){
//                return true;
//            }
//        }
//        return false;
//    }
//
//    //验证文件类型
//    @Override
//    public void validate() {
//        if(!filter(getAllowTypes().split(","))){
//            addFieldError("file","文件格式错误");
//        }
//    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public File getFile() {
        return file;
    }

    public void setFile(File file) {
        this.file = file;
    }

    public String getFileContentType() {
        return fileContentType;
    }

    public void setFileContentType(String fileContentType) {
        this.fileContentType = fileContentType;
    }

    public String getFileFileName() {
        return fileFileName;
    }

    public void setFileFileName(String fileName) {
        this.fileFileName = fileName;
    }

    //获取Struts.xml定义的保存路径
    public String getSavePath() {
//        System.out.println(ServletActionContext.getServletContext().getRealPath(savePath));
        return ServletActionContext.getServletContext().getRealPath(savePath);
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

//    public String getAllowTypes() {
//        return allowTypes;
//    }
//
//    public void setAllowTypes(String allowTypes) {
//        this.allowTypes = allowTypes;
//    }
}
